package com.cskaoyan.controller;

import com.cskaoyan.bean.data.PageData;
import com.cskaoyan.bean.vo.BaseRespVo;
import com.cskaoyan.model.MarketAddress;
import com.cskaoyan.service.AddressService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("wx/address")
public class WxAddressController {
    @Autowired
    AddressService addressService;

    @GetMapping("list")
    public BaseRespVo list() {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            Integer userId = (Integer) subject.getPrincipal();
            List<MarketAddress> addressList = addressService.list(userId);
            PageData pageData = PageData.list(addressList);
            return BaseRespVo.ok(pageData);
        }
        return BaseRespVo.unAuthc();
    }

    @GetMapping("detail")
    public BaseRespVo detail(Integer id) {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            Integer userId = (Integer) subject.getPrincipal();
            MarketAddress address = addressService.findAddrById(userId, id);
            if (address == null) {
                return BaseRespVo.badArgumentValue();
            }
            return BaseRespVo.ok(address);
        }
        return BaseRespVo.unAuthc();
    }

    @PostMapping("save")
    public BaseRespVo save(@RequestBody MarketAddress address) {
        //返回addressId
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            Integer userId = (Integer) subject.getPrincipal();
            Integer result = addressService.saveAddress(userId, address);
            return BaseRespVo.ok(result);
        }
        return BaseRespVo.unAuthc();
    }

    @PostMapping("delete")
    public BaseRespVo delete(@RequestBody Map<String, Integer> requestBody) {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            Integer userId = (Integer) subject.getPrincipal();
            Integer id = requestBody.get("id");
            Integer result = addressService.delete(userId, id);
            if (result == 1) {
                return BaseRespVo.ok(result);
            }
            return BaseRespVo.badArgumentValue();
        }
        return BaseRespVo.unAuthc();
    }
}
